package cn.hl.hm.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.UUID;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.apache.commons.httpclient.ProtocolException;
import org.apache.log4j.Logger;

import net.sf.json.JSONObject;

/**
 *  微信http调用工具类
 * @author hansheng
 *
 */
public class HttpUtil {
	
	// 日志对象声明
    private static Logger logger = Logger.getLogger("HttpUtil");
	 public static JSONObject httpsRequestToJsonObject(String requestUrl, String requestMethod, String outputStr) {
		  JSONObject jsonObject = null;
		  try {
		  StringBuffer buffer = httpsRequest1(requestUrl, requestMethod, outputStr);
		  jsonObject = JSONObject.fromObject(buffer.toString());
		  } catch (ConnectException ce) {
			  logger.info("连接超时："+ce.getMessage());
		  } catch (Exception e) {
			  logger.info("https请求异常："+e.getMessage());
		  }
		  return jsonObject;
		 }
		  
		 private static StringBuffer httpsRequest1(String requestUrl, String requestMethod, String output)
		  throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException, MalformedURLException,
		  IOException, ProtocolException, UnsupportedEncodingException {
		  URL url = new URL(requestUrl);
		  HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
		  connection.setDoOutput(true);
		  connection.setDoInput(true);
		  connection.setUseCaches(false);
		  connection.setRequestMethod(requestMethod);
		  if (null != output) {
		  OutputStream outputStream = connection.getOutputStream();
		  outputStream.write(output.getBytes("UTF-8"));
		  outputStream.close();
		  }
		  // 从输入流读取返回内容
		  InputStream inputStream = connection.getInputStream();
		  InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		  BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		  String str = null;
		  StringBuffer buffer = new StringBuffer();
		  while ((str = bufferedReader.readLine()) != null) {
		  buffer.append(str);
		  }
		  bufferedReader.close();
		  inputStreamReader.close();
		  inputStream.close();
		  inputStream = null;
		  connection.disconnect();
		  return buffer;
		 }
		 
		 //随机字符串：我用的是UUID去中划线
		 public static String create_nonce_str() {
			 return UUID.randomUUID().toString().replace("-","");
		 }
	/**
     * 发起https请求并获取结果
     * 
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr 提交的数据
     * 
     */
    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyTrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod.toUpperCase());

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
        	logger.error("Weixin server connection timed out.");
        } catch (Exception e) {
        	logger.error("https request error:{}", e);
        }
        return null;
    }
    
    
}
